package cn.aspart.async.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class CalculateService {

    @Async("specificAsyncExecutor")
    public CompletableFuture<Integer> add(Integer a, Integer b) {
//        sleep(3L);
//        return CompletableFuture.supplyAsync(() -> a + b);
        a = a + b;
        log.info("a and b is {}", a);
        CompletableFuture<Integer> future = new CompletableFuture<>();
        future.complete(a);
        return future;
    }

    @Async("specificAsyncExecutor")
    public CompletableFuture<Integer> sub(Integer a, Integer b) {
//        sleep(3L);
//        return CompletableFuture.supplyAsync(() -> a - b);
        a = a - b;
        log.info("a sub b is {}", a);
        CompletableFuture<Integer> future = new CompletableFuture<>();
        future.complete(a);
        return future;
    }

    public int sum(Integer a, Integer b) {
        log.info("fast calculate {} + {}, sum is {}", a, b, a + b);
        return a + b;
    }


    private void sleep(long sec) {
        try {
            TimeUnit.SECONDS.sleep(sec);
        } catch (InterruptedException e) {
            // do nothing
        }
    }
}
